package com.klod.data.repository

import com.klod.data.mapping.*
import com.klod.ext.suspendTransaction
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.deleteWhere
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll
import org.koin.core.annotation.Single


interface UserRepositoryI {


    suspend fun findAll(): MutableList<UserBean>

    suspend fun findById(id: Int): UserBean?

    suspend fun findByAccount(account: String): UserBean?

    suspend fun addUser(bean: UserBean): Int

    suspend fun deleteUser(id: Int): Boolean

}


@Single
class UserRepository : UserRepositoryI {
    override suspend fun findAll(): MutableList<UserBean> = suspendTransaction {

        UserTable.selectAll().map(::daoToUserModel).toMutableList()
    }

    override suspend fun findById(id: Int): UserBean? = suspendTransaction {
//        listOf(UserTable.id,
//            UserTable.account,
//            UserTable.name,
//            UserTable.createDate,
//            UserTable.type)
        UserTable.selectAll(
        ).where {
            UserTable.id eq id
        }.map(
            ::daoToUserModel
        ).singleOrNull()
    }

    override suspend fun findByAccount(account: String): UserBean? = suspendTransaction {

        UserTable.selectAll()
            .where { UserTable.account eq account }
            .map(::daoToUserModel)
            .singleOrNull()
    }

    override suspend fun addUser(bean: UserBean): Int = suspendTransaction {

        UserTable.insert {
            it[name] = bean.name
            it[account] = bean.account
            it[password] = bean.password?:""
            it[createDate] = bean.createDate
            it[type] = bean.type
        }[UserTable.id]
//
    }

    override suspend fun deleteUser(id: Int): Boolean = suspendTransaction {
        UserTable.deleteWhere {
            (UserTable.id eq id)
        } == 1
    }
}